package com.gitee.feizns.web.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author feizns
 * @since 2019/7/16
 */
public abstract class JSONUtils {

    /**
     * 装换jsonArray
     * @param e
     * @return
     */
    public static JSONArray toJSONArray(Object... e) {
        JSONArray ret = new JSONArray();
        if ( e != null )
            Arrays.stream(e).forEach(ret::add);
        return ret;
    }

    /**
     * 装换
     * @param collection
     * @return
     */
    public static JSONArray toJSONArray(Collection<?> collection) {
        JSONArray ret = new JSONArray();
        if ( collection != null )
            collection.forEach(ret::add);
        return ret;
    }

    /**
     * 装换JSONObject..
     * @param obj
     * @return
     */
    public static JSONObject toJSONObject(Object obj) {
        return JSONObject.parseObject(JSONObject.toJSONString(obj));
    }

    /**
     * 装换为集合
     * @param obj
     * @param clz
     * @param <T>
     * @return
     */
    public static <T> List<T> toList(Object obj, Class<T> clz) {
        if ( obj != null ) {
            if ( obj instanceof JSONArray )
                return ((JSONArray) obj).toJavaList(clz);
            else if ( obj instanceof List )
                return (List<T>) obj;
        }
        return Collections.emptyList();
    }

}
